
function qiPortal(server, path)
{
	var
		_isServer = (server == null) ? false : server,
		_ICWinAuth = null,
		_ICWinNonAuth = null,
		_stop = false,
		_isAuth = false,
		_path = (path == null) ? '' : path,
		self = this;

	this.checkParent = checkParent;
	this.start = start;
	this.startAuthorized = startAuthorized;
	this.stop = stop;
	this.isServer = isServer;
	this.registerICWindow = registerICWindow;
	this.callFunction = callFunction;

	function isServer()
	{
		return _isServer;
	}

	function checkParent()
	{
		if ((window.opener == null) || (window.opener.closed))
		{
			// no parent anymore or parent closed, doesn't matter...
		}
		else
		{
			var instance = window.opener.portalIC;
			if (! instance)
				instance = window.opener.qiPortalInstance;

			if ((instance) && (instance.registerICWindow))
			{
				instance.registerICWindow(window, _isAuth);
			}
		}

		if (! _stop)
			window.setTimeout(self.checkParent, 2000);
	}

	function startAuthorized()
	{
		_isAuth = true;
		checkParent();
	}

	function start()
	{
		_isAuth = false;
		checkParent();
	}

	function stop()
	{
		_stop = true;
	}

	function registerICWindow(win, auth)
	{
		if (auth == true)
			_ICWinAuth = win;
		else
			_ICWinNonAuth = win;
	}
	
	function callFunction(auth, functionCode, functionParams)
	{
		if (auth)
		{
			if ((_ICWinAuth == null) || (_ICWinAuth.closed))
			{
				if (! functionParams)
					functionParams = "";

				_ICWinAuth = window.open(_path + "IC_Auth.aspx?functionCode=" + escape(functionCode) + "&functionParams=" + escape(functionParams), "IC_Auth", "status=yes,toolbar=no,menubar=no,location=no,resizable=yes,scrollbars=yes");
			}
			else
			if (_ICWinAuth.ICApp == null)
			{
				_ICWinAuth.location.replace(_path + "IC_Auth.aspx?functionCode=" + escape(functionCode) + "&functionParams=" + escape(functionParams));
				_ICWinAuth.focus();
			}
			else
			{
				_ICWinAuth.ICApp.callPortalFunction(functionCode, functionParams);
				_ICWinAuth.focus();
			}
		}
		else
		{
			if ((_ICWinNonAuth == null) || (_ICWinNonAuth.closed))
			{
				if (! functionParams)
					functionParams = "";

				_ICWinNonAuth = window.open(_path + "IC_NonAuth.aspx?functionCode=" + escape(functionCode) + "&functionParams=" + escape(functionParams), "IC_NonAuth", "status=yes,toolbar=no,menubar=no,location=no,resizable=yes,scrollbars=yes");
			}
			else
			if (_ICWinNonAuth.ICApp == null)
			{
				_ICWinNonAuth.location.replace(_path + "IC_NonAuth.aspx?functionCode=" + escape(functionCode) + "&functionParams=" + escape(functionParams));
				_ICWinNonAuth.focus();
			}
			else
			{
				_ICWinNonAuth.ICApp.callPortalFunction(functionCode, functionParams);
				_ICWinNonAuth.focus();
			}
		}
	} 
}